import cv2
import os, sys
import glob
import numpy as np
import time
import pdb
import argparse
from pathlib2 import Path

def arg_parser():
    parser = argparse.ArgumentParser("Extract video frames")
    parser.add_argument("--path_video", type=str, help="video path for extract")
    parser.add_argument("--path_save", type=str, help='save extraction frames')
    parser.add_argument("--override", action='store_true', help="if override origin frames")

    args = parser.parse_args()
    return args

if __name__ == "__main__":

    args = arg_parser()

    path_video = Path(args.path_video)
    path_save  = Path(args.path_save)

    # create data path
    path_save_frames = path_save.joinpath("frames")
    path_save_frames.mkdir(parents=True, exist_ok=True)
    print("save frames dir = ", {path_save_frames})

    # STEP1: extract frames
    count = 0
    postfix = ".jpg"
    cap = cv2.VideoCapture(str(path_video))
    length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

    while True:

        success, image = cap.read()
        if not success:
            break

        ipath_frame = path_save_frames.joinpath(f"frame-{count:04d}{postfix}")

        if args.override or not ipath_frame.exists():
            cv2.imwrite(str(ipath_frame), image)

        count += 1
        if count % 50 == 0:
            print(f"extract and save the {count}/{length}-th frame --> {ipath_frame}")
